package com.csdj.t309springboot.controller;


import com.csdj.t309springboot.common.WebResult;
import com.csdj.t309springboot.common.WebResultMsgCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionController {

    private Logger log = LoggerFactory.getLogger("exception");

    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public WebResult error(RuntimeException e){
        //将异常信息打印到日志
        log.error(e.getClass().getName(),e);
//        e.printStackTrace(); 这各方式只会打印到控制台
        return new WebResult(WebResultMsgCode.FAIL);
    }

    @ResponseBody
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public WebResult paramError(MissingServletRequestParameterException e){
        log.error(e.getClass().getName(),e);
        return new WebResult(WebResultMsgCode.NO_PARAMS,e.getMessage());
    }
}
